#include "StringBuilder.h"
#include "ArrayList.h"

BASE(StringBuilder,None,100)

//SHARED
IMPL(int, init)
{
    THIS->list = (List *)ArrayListI()->create();
	if(!THIS->list) return 0;

	return 1;
}

IMPL(void, destroy)
{
	D(THIS->list);
}

IMPL(String *, build)
{
	unsigned long int size = C(THIS->list,size)();
	unsigned long int i;

	char *buf = (char *)malloc(sizeof(char)*(THIS->length+1));
	if(!buf) return 0;

	String *result = StringI()->create();
	if(!result)
	{
		free(buf);
		return 0;
	}

	char *ptr = buf;
	for(i=0; i<size; i++)
	{
		char *str = (char *)C(THIS->list, get)(i);
		while(*str)
		{
			*ptr = *str;
			++ptr; ++str;
		}
	}
	*ptr = 0;

	result->ptr = buf;
	result->length = THIS->length;

	return result;
}

IMPL(int, append, String *str)
{
	if(!str) return 1;

	if( !C(THIS->list,add)(str) ) return 0;

	THIS->length += C(str,length)();

	return 1;
}

IMPL(int, prepend, String *str)
{
	if(!str) return 1;

	if( !C(THIS->list, insertAt)(0,str) ) return 0;

	THIS->length += C(str,length)();

	return 1;
}

IMPL(int, appendPChar, char *ptr)
{
	if(!ptr) return 1;

	P(String, str);
	if(!str) return 0;

	if( !C(str,setPChar)(ptr) ) RETURN 0;
	if( !C(THIS->list,add)(str) ) RETURN 0;

	THIS->length += C(str,length)();

	RETURN 1;
}

IMPL(int, prependPChar, char *ptr)
{
	if(!ptr) return 1;

	P(String, str);
	if(!str) return 0;

	if( !C(str,setPChar)(ptr) ) RETURN 0;
	if( !C(THIS->list,insertAt)(0,str) ) RETURN 0;

	THIS->length += C(str,length)();

	RETURN 1;
}

SETUP_IF(ENTRY(init), ENTRY(destroy),
ENTRY(build),
ENTRY(append), ENTRY(prepend),
ENTRY(appendPChar), ENTRY(prependPChar) )
